<?php


namespace app\home\controller;

use app\base\BaseController;
use app\home\severs\SaleContractDetailSever;
use think\facade\Db;
use think\facade\View;

/**
 * Class InventoryBalance
 * @package app\home\controller
 * 库存余额
 */
class InventoryBalance extends BaseController
{
    protected $table='stock_mx_view';
    protected $title='库存余额';
    private $sessionKey='pageInventoryBalance';

    /**
     * @return \json|\think\response\View
     * @throws \think\db\exception\DbException
     * date:2024/4/18
     */
// public function index()
//    {
//        $param=$this->param;
//        if (request()->isAjax()) {
//
//            $where[]=['mdId','>',0];
//            $where[]=['type','in',[3]];
////            foreach (['bar_code','mdName','specs','brand'] as $i){
////                if (isset($param[$i])&&$param[$i]){
////                    $where[]=[$i,'like',"%".$param[$i].'%'];
////                }
////            }
//            if (isset($param['keywords'])&&$param['keywords']){
//                $where[]=['bar_code|mdName|brand|specs|buyCode|taxCode|saleContractOrder','like',"%".$param['keywords'].'%'];
//            }
//            if (isset($param['brand'])&&$param['brand']){
//                $where[]=['brand','like',"%".$param['brand'].'%'];
//            }
//            if (isset($param['mdName'])&&$param['mdName']){
//                $where[]=['mdName','like',"%".$param['mdName'].'%'];
//            }
//            if (isset($param['specs'])&&$param['specs']){
//                $where[]=['specs','like',"%".$param['specs'].'%'];
//            }
//            if (isset($param['buyCode'])&&$param['buyCode']){
//                $where[]=['buyCode','like',"%".$param['buyCode'].'%'];
//            }
//            if (isset($param['taxCode'])&&$param['taxCode']){
//                $where[]=['taxCode','like',"%".$param['taxCode'].'%'];
//            }
//            if (isset($param['cght'])&&$param['cght']){
//                $where[]=['saleContractOrder','like',"%".$param['cght'].'%'];
//            }
//            if (isset($param['pName'])&&$param['pName']){
//                $where[]=['pName','like',"%".$param['pName'].'%'];
//            }
//            if (isset($param['stockNum'])&&$param['stockNum']){
//                $where[]=['stokcOrderNum','like',"%".$param['stockNum'].'%'];
//            }
//            if (isset($param['type'])&&$param['type']){
//                $types=$this->getAllSubIds($param['type']);
//                $types[]=$param['type'];
//                $where[]=['mdType','in',$types];
//            }
//            if (isset($param['warehouse_id'])&&$param['warehouse_id']){
//               $where[]=["wId","=",$param['warehouse_id']];
//            }
//            if (isset($param['times'])&&$param['times']){
//                $times=explode('~',$param['times']);
//                $where[]=['checkTime','between',$times];
//            }
//            session($this->sessionKey,$where);
//            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
//            $list = Db::name($this->table)
//                ->where($where)
//                ->field("*")
//                ->paginate($rows)->each(function ($item,$index){
//                    $whear1[]=['id','=',$item['saleContractDetailId']];
//                    $whear1[]=['status','=',4];
//                    $sIds=Db::name('sale_contract_detail')
//                        ->where($whear1)->column('saleContractDetailId');
//                    $item['outNum']=Db::name('stock_order_detail')
//                        ->where('status',2)
//                        ->where('saleContractDetailId','in',$sIds)
//                        ->where('type','in',[1,4])->sum('num');
//                    $item['hasNum']=$item['num']-$item['outNum'];
//                    $item['dayLong']=ceil((time()-strtotime($item['checkTime']))/86400);
//                    $item['lockNum']=$item['lockNum']?$item['lockNum']:0;
//                    $item['kcMoney']=$item['proPrice']*$item['hasNum'];
//                    $dj='';
//                    $je='';
//                    if ($item['type']==3){
//                        $dj=Db::name('sale_contract_detail')
//                            ->where('id',$item['saleContractDetailId'])
//                            ->value('bjPrice');
//                        $je=round($dj*$item['hasNum'],2);
//                    }
//                    $item['dj']=$dj;
//                    $item['je']=$je;
//                    return $item;
//                });
//            return table_assign(0, '', $list);
//        } else {
//            $warehouse=Db::name('warehouse')->where('status',1)->field('id,name')->select();
//            View::assign('warehouseList',$warehouse);
//            return view();
//        }
//
//    }
    public function index()
    {
        $param=$this->param;
        if (request()->isAjax()) {

            $where[]=['sod.type','in',[3,5]];
            $where[]=['sod.status','=',2];

            if (isset($param['brand'])&&$param['brand']){
                $where[]=['md.brand','like',"%".$param['brand'].'%'];
            }
            if (isset($param['mdName'])&&$param['mdName']){
                $where[]=['md.name','like',"%".$param['mdName'].'%'];
            }
            if (isset($param['specs'])&&$param['specs']){
                $where[]=['md.specs','like',"%".$param['specs'].'%'];
            }
            if (isset($param['buyCode'])&&$param['buyCode']){
                $where[]=['md.buyCode','like',"%".$param['buyCode'].'%'];
            }
            if (isset($param['taxCode'])&&$param['taxCode']){
                $where[]=['md.taxCode','like',"%".$param['taxCode'].'%'];
            }
            if (isset($param['cght'])&&$param['cght']){
                $where[]=['saleContractOrder','like',"%".$param['cght'].'%'];
            }
            if (isset($param['xsht'])&&$param['xsht']){
                $where[]=['scd.saleContractOrderNum','like',"%".$param['xsht'].'%'];
            }
            if (isset($param['pName'])&&$param['pName']){
                $where[]=['p.name','like',"%".$param['pName'].'%'];
            }
            if (isset($param['stockNum'])&&$param['stockNum']){
                $where[]=['so.orderNum','like',"%".$param['stockNum'].'%'];
            }
            if (isset($param['hsContract'])&&$param['hsContract']){
                $where[]=['sod.hsContract','like',"%".$param['hsContract'].'%'];
            }
            if (isset($param['sodType'])&&$param['sodType']){
                $where[]=['sod.type','=',$param['sodType']];
            }
            if (isset($param['tType'])&&$param['tType']){
                $where[]=['sod.sodType','=',$param['tType']];
            }

            if (isset($param['times'])&&$param['times']){
                $times=explode('~',$param['times']);
                $where[]=['so.checkTime','between',$times];
            }
            session($this->sessionKey,$where);
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $res = $this->createIndexData($where,$rows);
            return table_assign(0, '操作成功', $res['list'],'200','',[],['countNum'=>$res['count']]);
        } else {
            $warehouse=Db::name('warehouse')->where('status',1)->field('id,name')->select();
            View::assign('warehouseList',$warehouse);
            return view();
        }

    }

    public function createIndexData($where,$isPage=false)
    {
        $countSql=$sql1=Db::name('stock_order_detail')
            ->alias('sod')
            ->leftJoin('stock_order so','so.id=sod.orderId')
            ->leftJoin('material_dossier md','md.id=sod.mdId')
            ->leftJoin('purveyor p','p.id=so.punterId')
            ->leftJoin('sale_contract_detail scd','scd.id=sod.saleContractDetailId')
            ->where($where);
            $sql=$sql1->field("sod.*,so.orderNum as stokcOrderNum,so.checkTime,md.name as mdName,md.buyCode,md.taxCode,md.unit,md.specs,md.brand,p.name as pName,
            scd.saleContractOrderNum as xsht")
            ->order('sod.id DESC');
        if ($isPage){

            $list=$sql->paginate($isPage)->each(function ($item){
                $inTime=strtotime($item['checkTime']);
                $daylong=ceil((time()-$inTime)/86400);
                $item['dayLong']=$daylong;
                $lockNum=Db::name('sale_contract_lock')->where('status',1)
                    ->where('stockOrderDetailId',$item['id'])->sum('lockNum');
                $item['lockNum']=$lockNum;
                $hasNum=$item['num']-$lockNum;
                $item['hasNum']=$item['canUseNum']=$hasNum;
                $item['dj']=$item['sodPrice'];
                return $item;
            });
        }else{
            $list=$sql->select();
        }
        $ids=$countSql->column('sod.saleContractDetailId');
        $count=$countSql->sum('sod.num');
        $countLock=Db::name('sale_contract_lock')->where('status',1)
            ->where('buyContactMxId','in',$ids)->sum('lockNum');
        return ['count'=>$count-$countLock,'list'=>$list];
    }
    public function exportData()
    {
        $where=session($this->sessionKey);
        $list = Db::name($this->table)
            ->where($where)
            ->field("*")->select()->each(function ($item){
                $item['outNum']=$item['outNum']?$item['outNum']:0;
                $item['hasNum']=$item['num']-$item['outNum'];
                $item['dayLong']=ceil((time()-strtotime($item['checkTime']))/86400);
                $item['lockNum']=$item['lockNum']?$item['lockNum']:0;
                $item['kcMoney']=$item['proPrice']*$item['kcMoney'];
                return $item;
            });
        $title = [
//            'id' => 'ID',
            'typeName' => '分类',
            'bar_code' => '编码',
            'mdName' => '物料名称',
            'mdBrand' => '品牌',
            'specs' => '规格型号',
            'unit' => '单位',
            'warehouseName' => '仓库',
            'hasNum' => '数量',
        ];
        $name =$this->title;
        exportXlsData($name,$title,$list);
        exit();
    }


    public function seeLock()
    {
        $param=$this->request->param();
        $id=$param['id']??'';

        if ($this->request->post()){

            if (!$id){
                return table_assign(1,'参数缺失');
            }

            $where[]=['scl.status','=',1];
            $where[]=['scl.stockOrderDetailId','=',$id];
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list=Db::name('sale_contract_lock')
                ->alias('scl')
                ->leftJoin('sale_contract_detail scd','scd.id=scl.detailId')
                ->leftJoin('sale_contract sc','sc.id=scd.orderId')
                ->where($where)
                ->field('scl.*,sc.orderNum')
                ->paginate($rows);
            return table_assign(0,'获取成',$list);

        }else{

            view::assign('id',$id);
            return view('');
        }

    }

    public function cancelLock()
    {
        $id=$this->param['id']??'';
        if (!$id){
            return to_assign(1,'参数缺失');
        }

        $info=Db::name('sale_contract_lock')->where('id',$id)
            ->find();
        $stockInfo=Db::name('stock_order_detail')->where('id',$info['stockOrderDetailId'])->find();
        if ($stockInfo['sodType']!=1&&$stockInfo['sodType']!=5){
            return to_assign(1,'非备货产品，不能撤销');
        }
        $hasLx=Db::name('stock_order_detail')->where('status','>',-1)
            ->where('lockedId',$id)->count();
        if ($hasLx){
            return to_assign(1,'已有关联数据，不可撤回');
        }
        try {
            Db::name('sale_contract_lock')->where('id',$id)->update(['status'=>-1,'deleted'=>time()]);
//            Db::name('sale_contract_detail')->where('id',$stockInfo['saleContractDetailId'])->update(['lockStatus'=>2]);
            SaleContractDetailSever::changeLockStatus($stockInfo['saleContractDetailId']);
            $this->param['option']='撤销锁定';
            add_log('back', $id, $this->param,$this->title);
        }catch (\Exception $e){
            return to_assign(1,'操作失败：'.$e->getMessage());
        }
        return to_assign();
    }
}